#include "UpdateFetcher.h"  
#include "UpdateHandler.h"  

// Signal handler
static void catch_segv(int sig) {
    exit(0);
} 

CUpdateFetcher::CUpdateFetcher():running_(false) {
}   
  
CUpdateFetcher::~CUpdateFetcher() {  
}  

void CUpdateFetcher::Start(const std::list<SUpdateCategory>& update_category_list) {
    boost::mutex::scoped_lock lock(mutex_);

    if(!running_) {
        running_ = true;

        // Prevent SIGPIPE
        struct sigaction sa;
        sa.sa_handler = SIG_IGN;
        sigaction(SIGPIPE, &sa, 0);

        std::string server_addr("https://www.update.microsoft.com/v6/ClientWebService/client.asmx");
 
        try {
            CUpdateHandler::GlobalInit(); // Should call only once

            for(std::list<SUpdateCategory>::const_iterator iter = update_category_list.begin(); iter != update_category_list.end(); iter++) {
                boost::shared_ptr<CUpdateHandler> handler(new CUpdateHandler(*iter, server_addr));  
                update_handler_table_[*iter] = handler;
                handler->StartFetchUpdates();
            }
        }
        catch(...) {
        }

        return;
    }
}

void CUpdateFetcher::Stop() {
    boost::mutex::scoped_lock lock(mutex_);

    if(running_) {
        running_ = false;

        try {
            for(std::map<SUpdateCategory, boost::shared_ptr<CUpdateHandler> >::iterator it = update_handler_table_.begin(); it != update_handler_table_.end();) {
                it->second->Stop();
                update_handler_table_.erase(it++);
            }
            
            CUpdateHandler::GlobalCleanup(); // Should call only once
        }
        catch(...) {
        } 

        return;
    }  
}
